<template>
  <el-dialog
    :title="`${isEdit?'修改名称':'创建新应用'}`"
    :visible.sync="dialogVisible"
    :center="true"
    width="500px"
    :before-close="beforeClose">
    <el-form :model="fromData" :rules="rules" :disabled="loading" ref="form" label-width="80px" @submit.native.prevent>
      <el-form-item label="应用名称" prop="name">
        <el-input v-model.trim="fromData.name"></el-input>
      </el-form-item>
      <el-form-item label="应用图标" class="app-image-upload">
        <div v-if="svgClass" class="el-image">
          <app-icon :iconName="svgClass" ></app-icon>
        </div>
        <el-image
          v-else
          :src="iconUrl" 
          :preview-src-list="[iconUrl]">
        </el-image>
        <el-upload
          ref="upload1"
          action="/designCenter/app/uploadPic"
          :multiple="false"
          :with-credentials="true"
          :show-file-list="false"
          list-type="picture"
          accept="image/*"
          :on-change="(file,fileList)=>handleChange(file,fileList,'upload1')"
          :before-upload="beforeUpload"
          >
          <div><el-button size="small" round type="primary" @click.stop="chooseIcon">从图标库中选择</el-button></div>
          
          <div><el-button size="small" round type="primary">本地上传</el-button></div>
        </el-upload>
      </el-form-item>
      <el-form-item label="应用封面" class="app-image-upload">
        <el-image
          :src="url" 
          :preview-src-list="[url]">
        </el-image>
        <el-upload
          ref="upload2"
          action="/designCenter/app/uploadPic"
          :multiple="false"
          :with-credentials="true"
          :show-file-list="false"
          list-type="picture"
          accept="image/*"
          :on-change="(file,fileList)=>handleChange(file,fileList,'upload2')"
          :before-upload="beforeUpload"
          >
          <el-button size="small" round type="primary">本地上传</el-button>
          <div slot="tip" class="el-upload__tip" style="height:20px;line-height:20px">只能上传图像文件，且不超过1M</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button :loading="loading" round size="small" type="primary" style="width: 124px;" @click="ok">{{loading?'执行中...':'确 定'}}</el-button>
    </span>
    <chooseIcon ref="chooseIcon" @choose="chooseIconOk"/>  
  </el-dialog>
</template>

<script>
import chooseIcon from "../components/chooseIcon.vue"
export default {
  data(){
    return{
      isEdit:false,
      loading:false,
      uploadLoading:false,
      dialogVisible:false,
      fromData:{},
      rules:{
          name: [
            { required: true, message: '请输入应用名称' },
            { max: 20, message: '最大长度20字符' }
          ]
      },
      imgInfo:{},
      iconImgInfo:{},
      url:"",
      iconUrl:"",
      iconClass:""
    }
  },
  components:{
    chooseIcon
  },
  methods:{
    open(data){
      const defaultImg = require('@/assets/images/default.png')
      const defaultIconClass = "vp-application"
      if(this.$refs.upload1)this.$refs.upload1.clearFiles()
      if(this.$refs.upload2)this.$refs.upload2.clearFiles()
      this.imgInfo = {}
      this.iconImgInfo = {}
      if(data){
        this.isEdit = true
        this.fromData = JSON.parse(JSON.stringify(data))
        this.url = this.fromData.dcBizIcon || defaultImg

        switch (data.bizIconType || 1) {
          case 1:
            this.iconUrl = ""
            this.iconClass = data.bizIcon || defaultIconClass
            break;
          case 0:
            this.iconUrl = _ctxPath + data.bizIcon
            this.iconClass = "" 
            break;
          case 2:
            this.iconUrl = _ctxPath + data.bizIcon
            this.iconClass = ""
            break;
        }

      }else{
        this.fromData = {}
        this.isEdit = false
        this.url = defaultImg
        this.iconUrl = ""
        this.iconClass = defaultIconClass
      }
      if(this.$refs.form) this.$refs.form.resetFields()
      this.$nextTick(()=>{
        this.dialogVisible = true
      })
    },
    chooseIcon(){
      this.$refs.chooseIcon.open()
    },
    chooseIconOk(icon){
      this.iconClass = icon
      this.iconUrl = ""
      this.iconImgInfo = {}
    },
    ok(){
      this.$refs.form.validate()
      .then(()=>{
        this.loading = true
        if(this.isEdit){
          this.editApp()
        }else{
          this.createApp()
        }
      })
      .catch((err)=>{
        console.log(err)
      })
    },
    createApp(){
      const {appPicId="",appPicUrl=""} = this.imgInfo
      const bizIcon =  this.iconClass || this.iconImgInfo.appPicUrl || ""
      const bizIconType = this.iconClass ? 1 : 0
      this.api.createApp({bizName:this.fromData.name,appPicId,appPicUrl,createType:0,bizIcon,bizIconType,bizType:1})
      .then(res=>{
        if(res.code==200){
          this.$message({
            type: 'success',
            message:'创建成功!'
          });
          this.$emit('change')
        }else{
          this.$message({
            type: 'warning',
            message:res.message
          });
        }
      })
      .catch(()=>{
        this.$message({
          type: 'warning',
          message:'创建失败!'
        });
      })
      .finally(()=>{
        this.dialogVisible = false
        this.$nextTick(()=>{
          this.loading = false
        })
      })
    },
    editApp(){
      const {appPicId="",appPicUrl=this.fromData.dcBizIcon} = this.imgInfo
      const bizIcon =  this.iconClass || this.iconImgInfo.appPicUrl || this.fromData.bizIcon
      const bizIconType = this.getBizIconType()
      this.api.renameApp({appId: this.fromData.id,appNewName: this.fromData.name,appPicId,appPicUrl,bizIcon,bizIconType})
      .then(()=>{
        this.$message({
          type: 'success',
          message:'修改成功!'
        });
        this.$emit('change')
      })
      .catch(()=>{
        this.$message({
          type: 'warning',
          message:'修改失败!'
        });
      })
      .finally(()=>{
        this.dialogVisible = false
        this.$nextTick(()=>{
          this.loading = false
        })
      })
    },
    getBizIconType(){
       const bizIconType = this.iconClass ? 1 : 0
       if(this.iconClass) return 1
       if(this.iconImgInfo.appPicUrl) return 0
       return this.fromData.bizIconType
    },
    beforeClose(done){
      if(!this.loading) done()
    },
    beforeUpload(file,showErr = true){
        const isImg = /^image\//.test(file.type);
        const isLt = file.size / 1024 / 1024 <= 1;

        if (!isImg && showErr) {
          this.$message.error('请选择图像文件!');
        }
        if (!isLt && showErr) {
          this.$message.error('上传图像文件大小不能超过 1M!');
        }
        return isImg && isLt;
    },
    handleChange(file,fileList,name){
      if(file.status==="ready" && this.beforeUpload(file.raw,false)){
        this.uploadLoading = this.$loading({
          lock: true,
          text: '上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      }
      else{
        if(this.uploadLoading) this.uploadLoading.close();
      }

      if(file.status==="success"){
        this.$message({
            type: 'success',
            message: '上传成功!'
          });
        if(name === "upload2"){
          const {id:appPicId,url:appPicUrl} = file.response.data
          this.imgInfo = {appPicId,appPicUrl}
          this.url = file.url
        }
        if(name === "upload1"){
          const {id:appPicId,url:appPicUrl} = file.response.data
          this.iconImgInfo = {appPicId,appPicUrl}
          this.iconUrl = file.url
          this.iconClass = ""
        }
      }

      if(file.status==="fail"){
        this.$message({
          message: '图片上传失败',
          type: 'warning'
        });
      }
      
    }
  },
  computed:{
    svgClass(){
      if(!this.iconClass) return ""
      return this.iconClass.replace(/^vp/,'vcloud')
    }
  }
}
</script>
<style lang="scss" scoped>
.app-image-upload{
  & /deep/ .el-form-item__content{
    display: flex;
    align-items: center;
    position: relative;
    .el-button{
      width: 140px;
    }
    .el-image{
      position: relative;
      width: 130px;
      height: 120px;
      margin-right: 20px;
      border: 1px solid #c0ccda;
      border-radius: 6px;
      svg{
        color: #336CFB;
        position: absolute; 
        width: 40px;
        height: 40px;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
      }
    }
  }
}
</style>